<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Model;
use think\Db;
use think\Cache;
use think\Loader;
use think\Lang;
// 设定当前语言
Lang::range('zh-cn');

class Index extends Model
{
    /**
     * 定义登录失败错误集
     * @var [array]
     */
    protected $errorLogin = [
        0 => '账号不存在！',
        1 => '密码错误！',
        2 => '传入登录信息有误！',
		3 => '该账号不允许在本机登录！',
    ];


    /**
     * 用户登录
     * @param  [array] $data [登录验证信息]
     * @return [array/bool]  [返回错误信息/登录成功返回true]
     */
    public function userLogin ($data)
    {
        // 判断是否正确传入登录信息
        if (!is_array($data)) return $this->errorLogin[2];
        // 查询是否存在该用户账号
        //$result_username = Db::name('sys_users')->where('username="'.$data['username'].'"')->find(); // 用工号登录
        $result_cn_name = Db::name('sys_users')->where('cn_name="'.$data['username'].'"')->find(); // 用中文名登录
        if ($result_cn_name === null) return $this->errorLogin[0];
        /*print_r($this->get_client_ip());exit;*/
        
        //判断IP范围
		if($result_cn_name['start_ip']){
			$user_IP = $this->get_client_ip();
			$ip_start = $this->get_iplong($result_cn_name['start_ip']); //起始ip  
			$ip_end = $this->get_iplong($result_cn_name['end_ip']);//至ip  
			$ip = $this->get_iplong($_SERVER["REMOTE_ADDR"]);//判断的ip  
			//可以这样简单判断  
			if($ip<=$ip_start || $ip >=$ip_end){  
				return $this->errorLogin[3];  
			}
		}
		// 判断密码是否正确 并尝试查询用户信息
		// 用中文名登录
		$where = array(
			'cn_name' => $data['username'],
			'password' => $data['password'],
		);
		$result = Db::name('sys_users')->alias('u')->join('xy_sys_role r', 'u.r_id = r.r_id')->field('u.*, r.action_list')->where($where)->find();
        
        if ($result === null) return $this->errorLogin[1];
        // 判断当前账号是否允许登录
        

        // 判断回访任务 保存结果 释放客户资料
        $this->releaseTask($result['username']);
        // 登陆成功
        // 记录登录信息 // 不管记没记下都返回true
        $result['password'] = md5($data['password']); // 密码不存明文
        // 查询目标 有就储存
        $daily =  Db::name('sys_daily_target')->where('username="'.$result['username'].'" AND createtime > "'.date('Y-m-d').'"')->order('createtime DESC')->find(); // 日目标
        if($daily) {
            $_SESSION['target']['daily'] = $daily['target'];
        } else {
            $_SESSION['target']['daily'] = null;
        }

        $monthly =  Db::name('sys_monthly_target')->where('username="'.$result['username'].'" AND createtime > "'.date('Y-m').'"')->order('createtime DESC')->find(); // 月目标
        if($monthly) {
            $_SESSION['target']['monthly'] = $monthly['target'];
            // 查询已通过的订单金额
            $fields = "
                sum(if(`order_status` = '1',`cope_money`,'0')) as adopt_money
            ";
            $sql = "SELECT $fields FROM `xy_order_info` WHERE `createname` = '".$result['username']."' AND `createtime` > '".date('Y-m')."-01 00:00:00'";
            $order = Db::query($sql);
            $adopt_money = $order[0]['adopt_money'];
            $_SESSION['target']['adopt_money'] = $adopt_money;
            $_SESSION['target']['complete'] = round(($adopt_money/$_SESSION['target']['monthly']*100)).'%';
        } else {
            $_SESSION['target']['monthly'] = null;
        }


        /**
         * 验证登录方法
         * 获取$_COOKIE['login_mark'], $_COOKIE['password']
         * 获取$_SESSION['userinfo']['login_mark']
         * 判断 是否 md5($_SESSION['userinfo']['login_mark'].$_COOKIE['password']) === $_COOKIE['login_mark']
         */
        $result['login_mark'] = md5(time().mt_rand(100000, 999999));
        // 获取分机
        $extension = Cache::get('extension'); // 分机绑定缓存
        $login_IP = $this->get_client_ip(); // 登录IP
        $user_exten = $extension[$login_IP];
        // print_r($result);exit;
        // 如果当前IP绑定了分机 择用绑定的分机
        if ($user_exten) {
            $result['extension'] = $user_exten;
        }
        // 更改登录时间
        $login_time = Db::name('sys_users')->where("username ='".$result['username']."'")->update(['login_datetime' => date('Y-m-d H:i:s')]);
        $result['login_datetime'] =  date('Y-m-d H:i:s');

        $_SESSION['user_info'] = $result; // 存入SESSION user_info
        $_SESSION['user_priv'] = json_decode($result['action_list'], true); // 存入SESSION user_priv

        $result['login_mark'] = md5($result['login_mark'].$result['password']);
        setcookie('login_mark', $result['login_mark'], 0, '/'); // 存入cookie login_mark
        setcookie('username', $result['username'], 0, '/'); // 存入cookie username
        setcookie('password', $result['password'], 0, '/'); // 存入cookie password
        
        // 返回true
        return true;
    }


    /**
     * 释放到期回访任务的客户资料
     */
    public function releaseTask () 
    {
        // 查询所有 到期并且未释放客户资料的任务id
        $result = Db::name('vip_task')->field('id')->where('endtime < "'.date('Y-m-d H:i:s').'" AND task_release="N"')->select();
        // print_r($result);
        if (empty($result)) return false; // 操作太多 确保不每次都瞎鸡巴执行 每天只卡第一个登录的
        $users = Cache::get('users');
        $visit = Cache::get('visit');
        foreach ($result as $v) {
            // 获得当前任务的所有回访记录
            $res = Db::name('vip_customer_basic')->alias('b')
                ->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')
                ->join('xy_vip_visit_record r','b.customer_code = r.customer_code AND b.task_id = r.task_id')
                ->field('b.customer_code,b.name,b.task_id,b.create_user,d.integral,r.visit_result_id,r.visit_type_id,r.create_time')
                ->where('b.task_id = "'.$v['id'].'"')->select();
            
            // 查询订单
            foreach ($res as &$val) {
                $order = Db::name('order_info')->field('order_goods_num,cope_money')->where('task_id = "'.$v['id'].'" AND customer_code = "'.$val['customer_code'].'"')->find();
                // var_dump($order);exit;
                if ($order) {
                    $val = array_merge($val, $order); 
                }
                $val['create_user'] = $users[$val['create_user']]['cn_name'];
                $val['visit_type_id'] = $visit['visit_type'][$val['visit_type_id']]['visit_type'];
                $val['visit_result_id'] = $visit['visit_result'][$val['visit_result_id']]['result_name'];
            }

            $arrData["code"] = 0;
            $arrData["msg"] = '';
            // $arrData["count"] = $count;
            $arrData["data"] = $res;
            $jsonData = json_encode($arrData);
            // 更改任务状态
            Db::name('vip_task')->where('id = '.$v['id'])->update(['task_release'=>'Y', 'task_result'=>$jsonData]);
            // 释放客户资料
            Db::name('vip_customer_basic')->where('task_id = '.$v['id'])->setField('task_id', null);
        }
    }


    public function doSetTarget ()
    {
        $type = $_REQUEST['type'];

        $data = array(
            'target' => $_REQUEST['target'],
            'username' => $_SESSION['user_info']['username'],
            'createtime' => date('Y-m-d H:i:s')
        );
        if ($type == 'daily') {
            $result = Db::name('sys_daily_target')->insert($data);
            $_SESSION['target']['daily'] = $data['target'];
        } elseif ($type == 'monthly') {
            $result = Db::name('sys_monthly_target')->insert($data);
            $_SESSION['target']['monthly'] = $data['target'];
        }

        if ($result) {
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
        // print_r($data);exit;
    }


    public function getTarget ()
    {
        // 先判断有没有 日目标
        if (empty($_SESSION['target']['daily'])) {
            echo '0';
            exit;
        }

        // 查询已通过的订单金额
        $fields = "
            sum(if(`order_status` = '1',`cope_money`,'0')) as adopt_money
        ";
        $sql = "SELECT $fields FROM `xy_order_info` WHERE `createname` = '".$_SESSION['user_info']['username']."' AND `createtime` > '".date('Y-m-d')." 00:00:00'";
        $result = Db::query($sql);
        $adopt_money = $result[0]['adopt_money'];
        $complete = round(($adopt_money/$_SESSION['target']['daily']*100));
        echo $complete;
    }



	/** 
	 * 将ip地址转换成int型 
	 * @param $ip  ip地址 
	 * @return number 返回数值 
	 */  
	public function get_iplong($ip){  
		//bindec(decbin(ip2long('这里填ip地址')));  
		//ip2long();的意思是将IP地址转换成整型 ，  
		//之所以要decbin和bindec一下是为了防止IP数值过大int型存储不了出现负数。  
		return bindec(decbin(ip2long($ip)));  
	} 
	
	//取IP地址
	public function get_client_ip(){
		if ($_SERVER['REMOTE_ADDR']) {
		$cip = $_SERVER['REMOTE_ADDR'];
		} elseif (getenv("REMOTE_ADDR")) {
		$cip = getenv("REMOTE_ADDR");
		} elseif (getenv("HTTP_CLIENT_IP")) {
		$cip = getenv("HTTP_CLIENT_IP");
		} else {
		$cip = "unknown";
		}
		return $cip;
	}
	
    /**
     * 系统目录菜单Index
     * @return [arr] [菜单目录]
     */
    public function index()
    {
        $r_id = $_SESSION["user_info"]["r_id"];
        $arrTenantRoles = $this->getTenantRoles();
        $thisTenantRole = $arrTenantRoles[$r_id];

        //从数据库中读取菜单
        $tpl_menu = Array();
        $where = "( 1";
        
        $where .= " ) AND mo.enabled='Y' "; //AND me.pid=0
        $where_sub = "1 ";
        
        $arrUser = Db::table('xy_sys_role')->where('r_id',1)->find();
        //$_SESSION["user_priv"] = json_decode( $arrUser['action_list'],true);//权限

        $user_priv = $_SESSION["user_priv"];
        foreach($user_priv as $key=>$val){
            if( in_array($key,$thisTenantRole)){
                $arrK[] = $key;
            }
            foreach($user_priv[$key] as $k=>$v){
                if( in_array($k,$thisTenantRole) ){
                    $arrK[] = $k;
                }
            }
        }
        $arrMData = Db::table('xy_sys_menu')->field("me.id AS id,me.icon as iconCls,me.name,me.moduleclass, me.order,me.url,me.pid AS pid")->alias('me')->join('sys_module mo','me.moduleclass=mo.modulename')->where($where)->order("`order` ASC")->select();

        $arrMD = getTree($arrMData,"0","pid","id");
        $_SESSION['menu'] = Array();//存放子菜单的父菜单，为以后判断子菜单的权限的方便
        foreach($arrMD as $key=>&$val){
            //非admin用户只看已有的权限
            if( !in_array($val["name"],$arrK)  && $username != 'admin' ){
                unset($arrMD[$key]);
                continue;
            }
            $pid_menu = $val["name"];
            $val["name"] = Lang::get($val["name"]);
            foreach($val["subMenu"] as $km=>&$vm){
                //非admin用户只看已有的权限
                if( !in_array($vm["name"],$arrK) ){
                    unset($val["subMenu"][$km]);
                    continue;
                }
                $_SESSION['menu'][$vm['name']] = $pid_menu;
                $vm["name"] = Lang::get($vm["name"]);
            }
            //非admin用户只看已有的权限
            //sort($val["subMenu"]);
            $val["subMenu"] = array_sort($val["subMenu"],'order','asc',"no");
        }
        $arrMenu = array_sort($arrMD,'order','asc',"no");
        return $arrMenu;
    }

    /**
     * 获取坐席权限
     * @return [arr] [坐席权限]
     */
    public function getTenantRoles(){
        $arrData = Db::table('xy_sys_role')->select();
        $arrF = array();
        foreach($arrData as &$val){
            $val["action_list"] = json_decode($val["action_list"],true);
            // if ($val["action_list"]) {
                foreach($val["action_list"] as $k=>$v){
                    $arrK[] = $k;
                    foreach($val["action_list"][$k] as $km=>$vm){
                        $arrK[] = $km;
                    }
                }
            // }
            
            $val["action_key"] = $arrK;
            $arrF[$val["r_id"]] = $val["action_key"];
            unset($arrK);
        }
        return $arrF;
    }
	
	public function settingPassword()
	{
		$username = $_REQUEST['username'];
		$result = Db::name('sys_users')->where("username ='".$_REQUEST['username']."'")->update(['password' => $_REQUEST['password']]);
        if ($result){
			unset($_SESSION['user_info']);
			unset($_SESSION['user_priv']);
			setcookie('login_mark', $result['login_mark'], -1, '/'); // 存入cookie login_mark
			setcookie('username', $result['username'], -1, '/'); // 存入cookie username
			setcookie('password', $result['password'], -1, '/'); // 存入cookie password
			echo true;
        } else {
            echo json_encode(array('msg'=>'密码设置失败！'));
        }

	}


    public function realtimeData ()
    {
        $fields = "
            count(*) as total,
            sum(if(`order_status` = '1','1','0')) as adopt_num,
            sum(if(`order_status` = '1',`cope_money`,'0')) as adopt_money
        ";


        $sql = "SELECT $fields FROM `xy_order_info` WHERE  `createtime` > '".date('Y-m-d')." 00:00:00'";
        $result = Db::query($sql);
        $result = $result[0];
        foreach ($result as &$val) {
            if (empty($val)) $val = 0;
        }
        $result['adopt_rate'] = round(($result['adopt_num']/$result['total'])*100, 2)."%";
        // $result = Db::name('order_info')->field($fields)->fetchSql(true)->whereTime('createtime', 'today')->select();
        // print_r($result);exit;
        echo json_encode($result);

    }


    public function orderData ()
    {
        $date = date('Y-m-d');
        $fields = "
            count(*) as total,
            sum(if(`order_status` = '1','1','0')) as adopt_num,
            DATE_FORMAT(createtime,'%H') as hours
        ";
        $result = Db::name('order_info')->field($fields)->where('createtime LIKE "'.$date.' %"')->group("DATE_FORMAT(createtime,'%Y-%m-%d %H')")->order("DATE_FORMAT(createtime,'%Y-%m-%d %H') ASC")->select();
        // print_r($result);exit;
        echo json_encode($result);

    }


    public function customerGroupCount ()
    {
        $time1 = date('Y-m-d H:i:s', time()-30*24*3600);
        $time2 = date('Y-m-d H:i:s', time()-60*24*3600);
        $time3 = date('Y-m-d H:i:s', time()-90*24*3600);
        $time4 = date('Y-m-d H:i:s', time()-180*24*3600);


        $fields = "
            sum(if(`last_order_time` < '$time1','1','0')) as one_month,
            sum(if(`last_order_time` < '$time2','1','0')) as two_month,
            sum(if(`last_order_time` < '$time3','1','0')) as three_month,
            sum(if(`last_order_time` < '$time4','1','0')) as six_month
        ";

        $where = "last_order_time is not null";


        $sql = "SELECT $fields FROM `xy_vip_customer_detail` WHERE $where ";
        $result = Db::query($sql);
        // $result = Db::name('order_info')->field($fields)->fetchSql(true)->whereTime('createtime', 'today')->select();
        // print_r($result);exit;
        echo json_encode($result[0]);

    }


    public function pictureData ()
    {
        $pictureDataList = Db::name('sys_picture')->where('display="Y"')->order('`order` ASC')->select();
        return $pictureDataList;
    }


}